package com.jxy.homepage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jxy.BBM_info.BBM;
import com.jxy.BBM_info.BBM_table;
import com.jxy.BBM_info.utils.BBM_util;
import com.jxy.homepage.domain.Article;
import com.jxy.homepage.mapper.ArticleMapper;
import com.jxy.homepage.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * ArticleServiceImpl
 *
 * @author Jxy
 * @date 2022/1/28
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    BBM bbmResponse = new BBM();

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public BBM doArticle(BBM bbm) {
        BBM_table ins = bbm.getTable("ARTICLE_INS");
        if (ins != null) {
            // 成功
            try {
                boolean b = this.saveBatch(ins.toBean(Article.class), 1000);
                if (b) {
                    bbmResponse.getBbmInfo().setCode(1);
                    bbmResponse.getBbmInfo().setMessage("success insert");
                }
            } catch (Exception e) {
                bbmResponse.getBbmInfo().setCode(-1);
                bbmResponse.getBbmInfo().setMessage(e.getMessage());
            }
        } else {
            // 失败
            bbmResponse.getBbmInfo().setCode(-1);
            bbmResponse.getBbmInfo().setMessage("Failed to get data");
        }
        return bbmResponse;
    }

    @Override
    public BBM getArticle(BBM bbm) {
        BBM_table table = bbm.getTable("ARTICLE_Q");
        if (table != null && table.getRows().size() > 0) {
            QueryWrapper<Article> wrapper = new QueryWrapper<>();
            wrapper.eq("USER_ID", table.getRowValue(0, "USER_ID"));
            wrapper.eq("ENV_TYPE", table.getRowValue(0, "ENV_TYPE"));
            wrapper.eq("VERSION", table.getRowValue(0, "VERSION"));
            List<Article> list = this.list(wrapper);
            BBM_table table1 = BBM_util.toTable(list, Article.class);
            bbmResponse.getBbmTables().clear();
            bbmResponse.addTable(table1);
        } else {
            // 失败
            bbmResponse.getBbmInfo().setCode(-1);
            bbmResponse.getBbmInfo().setMessage("Failed to get data");
        }
        return bbmResponse;
    }
}
